package com.bmicpd.gzh.controller;

import com.bmicpd.gzh.vo.ResultVo;
import com.google.common.collect.Lists;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.List;
import java.util.Map;


/**
 * @author       ytree
 */
@RestController
public class GzhSearchController {

    private Logger logger = LoggerFactory.getLogger(GzhSearchController.class);

    @Value("${ElasticSearch.HOST}")
    private String esHost;

    @Value("${ElasticSearch.PORT}")
    private int esPort;

    @Value("${ElastisSearch.INDEX}")
    private String esIndex;

    @Value("${ElasticSearch.TYPE}")
    private String esType;

    @Value("${search.result.page.size}")
    private int pageSize;

    @RequestMapping(value = "/es", method = RequestMethod.GET)
    public ResultVo esSearch(@RequestParam String query, String page){

        logger.info("query : {}", query);
        int pageInt = Integer.parseInt(page);
        List<Map<String, Object>> list = Lists.newArrayList();
        // 创建客户端
        try (TransportClient client = new PreBuiltTransportClient(Settings.EMPTY).addTransportAddresses(
                new InetSocketTransportAddress(InetAddress.getByName(esHost),esPort))){
            logger.info("Elasticsearch connect info: {}", client);

            assert client != null;
            SearchRequestBuilder searchRequestBuilder = client.prepareSearch(esIndex)
                    .setTypes(esType).setTimeout(TimeValue.timeValueMillis(500))
                    .setQuery(QueryBuilders.matchPhraseQuery("irContent", query));
            long totalHits = searchRequestBuilder.get().getHits().getTotalHits();
            logger.info("query total : {}", totalHits);

            // 每次只获取15条结果
            SearchResponse searchResponse = searchRequestBuilder
                    .setFrom(pageInt * pageSize).setSize(pageSize).execute().actionGet();
            SearchHit[] hits = searchResponse.getHits().hits();
            for(SearchHit hit : hits){
                list.add(hit.getSource());
            }

            logger.info(" query list size : {}", list.size());
            return new ResultVo("0", "ok", list);
        } catch (UnknownHostException e) {
            logger.error("Host 未知异常 ： {}", e);
        }

        return new ResultVo("-1", "err", list);
    }

    /**
     * 根据时间来排序
     * @param page 分页
     * @return ResultVo
     */
    @RequestMapping(value = "/es_search_by_date", method = RequestMethod.GET)
    public ResultVo esSearchByDate(@RequestParam String page){

        int parseInt = Integer.parseInt(page);
        List<Map<String, Object>> list = Lists.newArrayList();
        try (TransportClient client = new PreBuiltTransportClient(Settings.EMPTY).addTransportAddresses(
                new InetSocketTransportAddress(InetAddress.getByName(esHost), esPort))){

            logger.info("Elasticsearch connect info: {}", client);

            assert client != null;
            SearchRequestBuilder searchRequestBuilder = client.prepareSearch(esIndex)
                    .setTypes(esType).setFrom(parseInt * pageSize).setSize(pageSize)
                    .addSort("irUrlTime.keyword", SortOrder.DESC);
            long totalHits = searchRequestBuilder.get().getHits().getTotalHits();
            logger.info("query total : {}", totalHits);

            // 每次只获取15条结果
            SearchResponse searchResponse = searchRequestBuilder
                    .execute().actionGet();
            logger.info("searchResponse : {}", searchResponse);
            SearchHit[] hits = searchResponse.getHits().hits();
            logger.info("hits : {}", hits);
            for(SearchHit hit : hits){
                list.add(hit.getSource());
            }

            logger.info(" query list size : {}", list.size());

            return new ResultVo("0", "ok", list);
        } catch (UnknownHostException e) {
            logger.error("Host 未知异常 ： {}", e);
        }

        return new ResultVo("-1", "err", list);

    }

}
